package com.zl.dao;

import java.sql.Connection;
import java.sql.ResultSet;

import com.mysql.jdbc.PreparedStatement;
import com.zl.model.User;
import com.zl.util.ZLString;

public class UserDao {

	public static User login(Connection con, User user) throws Exception {
		
		User backUser = null;

		String sql = "select * from t_user where userName = ? and password = ?";
		
		PreparedStatement statement = (PreparedStatement) con.prepareStatement(sql);
		
		statement.setString(1, user.getUserName());//给sql中第一个？设置值
		statement.setString(2, user.getPassword());
		
		ResultSet set = statement.executeQuery();//执行sql并返回一个结果集
		
		if (set.next()) {
			
			backUser = new User();
			//从返回的结果集中取对应的数据并赋值
			backUser.setId(set.getInt("id"));
			backUser.setUserName(set.getString("userName"));
			backUser.setPassword(set.getString("password"));
			backUser.setIsAdmin(set.getBoolean("isAdmin"));
		}
		
		return backUser;
	}
	
	public static ResultSet select(Connection connection, User user) throws Exception {
		
		StringBuffer buffer = new StringBuffer("select * from t_user");
		
		if (ZLString.isNotEmpty(user.getUserName())) {
			buffer.append(" where userName like '%"+ user.getUserName() +"%'");
		}

		PreparedStatement statement = (PreparedStatement) connection.prepareStatement(buffer.toString());
		
		return statement.executeQuery();
	}
	
}
